﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;

namespace KPI_SYSTEM.Code
{
    /// <summary>
    /// SubApproval 的摘要说明
    /// </summary>
    public class SubApproval : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            try
            {
                String approvalDataID = context.Request.Form["approvalDataID"];
                String approvalMenuName = context.Request.Form["approvalMenuName"];
                String approvalPageName = context.Request.Form["approvalPageName"];
                String approvalID = context.Request.Form["approvalID"];
                DataTable tableApprovalMessage = SqlHelper.ExecuteDataset(CommandType.Text, "SELECT * FROM HOS_APPROVAL_MAIN WHERE REC_ID=" + approvalID).Tables[0];
                DataTable tableProcessMessage = SqlHelper.ExecuteDataset(CommandType.Text, @"SELECT *,(SELECT STUFF((SELECT ','+ PROCESS_USER FROM HOS_APPROVAL_PROCESS
                                                                                             FOR XML PATH('')), 1, 1, '')) AS PROCESS_USER_ID
                                                                                             FROM HOS_APPROVAL_PROCESS WHERE APPROVAL_ID=" + approvalID + " ORDER BY PROCESS_SEQ ").Tables[0];
                DataTable tableCheck = SqlHelper.ExecuteDataset(CommandType.Text, "SELECT * FROM HOS_APPROVAL_RECORDS WHERE APPROVAL_ID=" + approvalID + " AND APPROVAL_DATA_ID=" + approvalDataID).Tables[0];
                Int32 processUserCount = tableProcessMessage.Rows[0]["PROCESS_USER_ID"].ToString().Split(',').Count();
                if (tableCheck.Rows.Count <= processUserCount && tableCheck.Select("PROCESS_RESULT=" + (int)PROCESS_RESULT.审核未通过).Count() <= 0 && tableCheck.Rows.Count > 0)
                {
                    context.Response.Write("{\"success\":false,\"message\":\"当前数据存在未完成审批记录！\"}");
                }
                else if (tableCheck.Rows.Count <= processUserCount && tableCheck.Select("PROCESS_RESULT=" + (int)PROCESS_RESULT.审核未通过).Count() > 0 && tableCheck.Rows.Count > 0)
                {
                    SqlHelper.ExecuteNonQuery(CommandType.Text, "DELETE FROM HOS_APPROVAL_RECORDS WHERE APPROVAL_ID=" + approvalID + " AND APPROVAL_DATA_ID=" + approvalDataID);
                    foreach (DataRow dataRow in tableProcessMessage.Rows)
                    {
                        foreach (String item in dataRow["PROCESS_USER"].ToString().Split(','))
                        {
                            SaveApprovalProcess(approvalID, dataRow["REC_ID"].ToString(), approvalDataID, dataRow["PROCESS_DEPT"].ToString(),
                                                item, dataRow["PROCESS_TYPE"].ToString(), approvalPageName,
                                                context.Session["UserID"].ToString(), context.Session["UserDept"].ToString(),dataRow["PROCESS_SEQ"].ToString(), approvalMenuName);
                        }
                    }
                   
                    context.Response.Write("{\"success\":true,\"message\":\"提交审核成功！\"}");
                }
                else
                {
                    foreach (DataRow dataRow in tableProcessMessage.Rows)
                    {
                        foreach (String item in dataRow["PROCESS_USER"].ToString().Split(','))
                        {
                            SaveApprovalProcess(approvalID, dataRow["REC_ID"].ToString(), approvalDataID, dataRow["PROCESS_DEPT"].ToString(),
                                                item, dataRow["PROCESS_TYPE"].ToString(), approvalPageName,
                                                context.Session["UserID"].ToString(), context.Session["UserDept"].ToString(), dataRow["PROCESS_SEQ"].ToString(), approvalMenuName);
                        }
                    }
                    context.Response.Write("{\"success\":true,\"message\":\"提交审核成功！\"}");
                }
            }
            catch (Exception ex)
            {
                context.Response.Write("{\"success\":false,\"message\":\"" + ex.Message + "\"}");
            }
            context.Response.End();
        }
        public void SaveApprovalProcess(String APPROVAL_ID,String PROCESS_ID,String APPROVAL_DATA_ID,String PROCESS_DEPT,
            String PROCESS_USER,String PROCESS_TYPE,String PROCESS_PAGE_NAME,String CREATE_USER,String SUB_DEPT,String PROCESS_SEQ,String MENU_NAME)
        {
            Dictionary<String, String> keyValuePairs = new Dictionary<string, string>();
            keyValuePairs.Clear();
            keyValuePairs.Add("APPROVAL_ID", APPROVAL_ID);
            keyValuePairs.Add("PROCESS_ID", PROCESS_ID);
            keyValuePairs.Add("APPROVAL_DATA_ID", APPROVAL_DATA_ID);
            keyValuePairs.Add("PROCESS_DEPT", PROCESS_DEPT);
            keyValuePairs.Add("PROCESS_USER", PROCESS_USER);
            keyValuePairs.Add("PROCESS_TYPE", PROCESS_TYPE);
            keyValuePairs.Add("SUB_USER", CREATE_USER);
            keyValuePairs.Add("PROCESS_SEQ", PROCESS_SEQ);
            keyValuePairs.Add("APPROVAL_CONTENT", MENU_NAME + "审核");//8
            keyValuePairs.Add("SUB_DEPT", SUB_DEPT);
            keyValuePairs.Add("SUB_TIME", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//10
            keyValuePairs.Add("PROCESS_RESULT", Convert.ToString((int)PROCESS_RESULT.待审核));
            keyValuePairs.Add("PROCESS_PAGE_NAME", PROCESS_PAGE_NAME);//11
            keyValuePairs.Add("CREATE_TIME", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//12
            keyValuePairs.Add("CREATE_USER", CREATE_USER);
            String sqlInsertRecords = @"INSERT INTO HOS_APPROVAL_RECORDS (APPROVAL_ID,PROCESS_ID,APPROVAL_DATA_ID,PROCESS_DEPT,PROCESS_USER,PROCESS_TYPE,SUB_USER,PROCESS_SEQ,
                                        APPROVAL_CONTENT,SUB_DEPT,SUB_TIME,PROCESS_RESULT,PROCESS_PAGE_NAME,CREATE_TIME,CREATE_USER) VALUES ({0},{1},{2},{3},{4},{5},{6},{7},'{8}',{9},'{10}'
                                        ,{11},'{12}','{13}',{14}) SELECT @@IDENTITY;";
            sqlInsertRecords = string.Format(sqlInsertRecords, APPROVAL_ID, PROCESS_ID, APPROVAL_DATA_ID, PROCESS_DEPT, PROCESS_USER, PROCESS_TYPE, CREATE_USER,
                                            PROCESS_SEQ, MENU_NAME + "审核", SUB_DEPT, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), (int)PROCESS_RESULT.待审核
                                            , PROCESS_PAGE_NAME, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), CREATE_USER);
            String recordID = SqlHelper.ExecuteScalar(CommandType.Text, sqlInsertRecords).ToString();

            String sqlInsertRecordsBak = @"INSERT INTO HOS_APPROVAL_RECORDS_BAK (APPROVAL_ID,PROCESS_ID,APPROVAL_DATA_ID,PROCESS_DEPT,PROCESS_USER,PROCESS_TYPE,SUB_USER,PROCESS_SEQ,
                                        APPROVAL_CONTENT,SUB_DEPT,SUB_TIME,PROCESS_RESULT,PROCESS_PAGE_NAME,CREATE_TIME,CREATE_USER,RECORD_ID) VALUES ({0},{1},{2},{3},{4},{5},{6},{7},'{8}',{9},'{10}'
                                        ,{11},'{12}','{13}',{14},{15})";
            sqlInsertRecordsBak = string.Format(sqlInsertRecordsBak, APPROVAL_ID, PROCESS_ID, APPROVAL_DATA_ID, PROCESS_DEPT, PROCESS_USER, PROCESS_TYPE, CREATE_USER,
                                          PROCESS_SEQ, MENU_NAME + "审核", SUB_DEPT, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), (int)PROCESS_RESULT.待审核
                                          , PROCESS_PAGE_NAME, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), CREATE_USER, recordID);
            SqlHelper.ExecuteNonQuery(CommandType.Text, sqlInsertRecordsBak);
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}